<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>doc view</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
</head>

<body>
    <div id="webConsole"><textarea readonly="readonly"></textarea></div>
    <div id="viewMain">
        <div id="viewBody" class="container"></div>
        <div id="loadPromt" class="view-loading">
            <div class="loading-img-container">
                <div class="page-hd">HD</div>
                <div class="page-indicator">1 / 1</div>
                <img id="view-loading-img" class="view-loading-img" src="img/loading.gif">
                <div id="view-loading-retry" class="view-loading-retry">
                    <div class="loading-retry-text"></div>
                    <div class="loading-retry-button" data-i18n="retry"></div>
                </div>
            </div>
        </div>
        <div class="footer text-muted" data-i18n="notice"></div>
    </div>

    <script src="js/jquery-3.3.1.min.js"></script>
    <script src="js/jquery.i18n.js"></script>
    <script src="js/jquery.i18n.messagestore.js"></script>
    <script src="js/main.js"></script>
    <script>
        (function ($) {
          var logger = $.logger

          var localUrlData = {}
          var authAllowed = false
          var pageDataReady = false
          var imgDataReady = false
          var win = $(window)
          var lazyLoadTimer
          var lastScrollPageBlock = -1
          var baseUrl

          var pageStep = 5
          var isInitPages = false
          var totalPages = 0
          var loadingImg = 'img/loading.gif'
          var pageMap = {}
          var remoteLoadLock = false
          var loadingParams = null
          var loadQueue = []

          $(function () {
            $('#viewMain').i18n()

            initJSAPI()

            win.scroll(function () {
              if (!imgDataReady) return
              if (typeof lazyLoadTimer !== 'undefined' && lazyLoadTimer != null) {
                clearTimeout(lazyLoadTimer)
              }
              lazyLoadTimer = setTimeout(scrollLoad, 200)
            })

            $.SDK.jsComplete()
          })

          function initJSAPI () {
            window.view = function (docViewUrl, sysCode, viewInfo, localCache) {
              logger.debug('SDK -> view(' + docViewUrl + ',' + sysCode + ',' + viewInfo + ',' + localCache + ')')
              baseUrl = docViewUrl
              $.initDocView(docViewUrl, sysCode, viewInfo)
              if (localCache) {
                var pageUrls = JSON.parse(localCache)
                if (typeof pageUrls === 'object') {
                  if (pageUrls.totalPages > 0 && typeof pageUrls.pages === 'object') {
                    localUrlData = pageUrls.pages
                    totalPages = pageUrls.totalPages
                    var pages = ''
                    for (var p in localUrlData) {
                      pages += ',' + p
                    }
                    logger.debug('本地缓存解析成功，totalPages:' + totalPages + '，pages:' + pages.substr(1))
                    initAllBlankPage()
                    isInitPages = true
                  }
                }
              }
              appendImg(1, pageStep)
              return '1'
            }

            window.authResult = function (code) {
              $.logger.debug('SDK -> authResult(' + code + ')')
              switch (code) {
                case '100':
                  authSuccess()
                  break
                case '101':
                  showRefuse(code)
                  break
                case '102':
                case '103':
                  showAuthRetry(code)
                  break
                default:
                  break
              }
              return '1'
            }

            window.cacheImgCallback = function (page, chunk, result, cacheUrl) {
              logger.debug('SDK -> cacheImgCallback(' + page + ',' + chunk + ',' + result + ',' + cacheUrl + ')')
              localUrlData[page.toString()] = cacheUrl
              return '1'
            }
          }

          var authSuccess = function () {
            $.logger.debug('已授权')
            authAllowed = true
            showView()
            authSuccess = showRefuse = showAuthRetry = $.noop
          }

          function showView () {
            if (!authAllowed || !pageDataReady) return
            $('#viewBody').show()
            $('.footer').show()
            $('#loadPromt').hide()
          }

          var showRefuse = function (code) {
            $.logger.debug('未授权')
            $('#viewBody').empty()
            $.throwError(code, null)
            authSuccess = showRefuse = showAuthRetry = $.noop
          }

          var showAuthRetry = function (code) {
            $.logger.debug('鉴权失败' + code)
            $.throwError(code, $.SDK.authRetry)
          }

          // 滚动停止时加载所在页图片
          function scrollLoad () {
            lazyLoadTimer = null
            if (totalPages === 0) return
            var startPage = getScrollPage()
            var pageBlock = parseInt((startPage + pageStep - 1) / pageStep) - 1
            if (pageBlock === lastScrollPageBlock) {
              return
            }
            lastScrollPageBlock = pageBlock
            startPage = pageBlock * pageStep + 1
            var endPage = Math.min(startPage + pageStep - 1, totalPages)
            var allLoaded = true
            for (var i = startPage; i <= endPage; i++) {
              var imgPage = $('#img_page_' + i)
              if (!imgPage.data('loaded')) {
                allLoaded = false
                break
              }
            }
            if (!allLoaded) {
              setState2Reload(startPage, endPage)
              appendImg(startPage, endPage)
            } else {
              setTimeout(scrollLoadNext, 200)
            }
          }

          function scrollLoadNext () {
            var startPage = getScrollPage()
            var pageBlock = parseInt((startPage + pageStep - 1) / pageStep) - 1
            $.logger.debug('准备预加载下一区块：' + (pageBlock + 1))
            if (lastScrollPageBlock > -1 && lastScrollPageBlock !== pageBlock) {
              $.logger.debug('已滚动至其他区块，取消预加载')
              return
            }
            startPage = (pageBlock + 1) * pageStep + 1
            if (startPage > totalPages) return
            var endPage = Math.min(startPage + pageStep - 1, totalPages)
            var allLoaded = true
            for (var i = startPage; i <= endPage; i++) {
              var imgPage = $('#img_page_' + i)
              if (!imgPage.data('loaded')) {
                allLoaded = false
                break
              }
            }
            if (!allLoaded) {
              $.logger.debug('预加载下一区块：' + startPage + '-' + endPage)
              setState2Reload(startPage, endPage)
              appendImg(startPage, endPage)
            } else {
              $.logger.debug('下一区块已加载：' + startPage + '-' + endPage)
            }
          }

          // 获取滚动后所在页码
          function getScrollPage () {
            var page = totalPages
            $('.img-container').each(function (i, o) {
              var target = $(o)
              if (target.offset().top >= (win.scrollTop() - 50) && target.offset().top < (win.scrollTop() + win.height())) {
                page = target.data('page')
                return false
              }
            })
            return parseInt(page)
          }

          function appendImg (startPage, endPage) {
            logger.debug('加载：' + startPage + '-' + endPage)
            var pageBlock = parseInt((startPage + pageStep - 1) / pageStep) - 1
            // 判断页块是否已经请求过
            if (pageMap[pageBlock.toString()]) {
              logger.debug('页块已加载：' + startPage + '-' + endPage)
              return
            }

            startPage = pageStep * pageBlock + 1
            if (totalPages > 0 && startPage > totalPages) {
              logger.warn('起始页超过总页数(' + totalPages + ')：' + startPage + '-' + endPage)
              return
            }
            endPage = startPage + pageStep - 1
            if (totalPages > 0 && totalPages < endPage) {
              logger.debug('结束页超过总页数(' + totalPages + ')：' + startPage + '-' + endPage)
              endPage = totalPages
            }

            // 先从本地寻找图片
            var missImg = false
            for (var i = startPage; i <= endPage; i++) {
              var img = $('#img_page_' + i)
              if (!img.data('loaded')) {
                if (localUrlData[i.toString()]) {
                  logger.debug('从本地缓存加载页：' + i + ', ' + localUrlData[i.toString()])
                  img.data('from', 'local').attr('src', localUrlData[i.toString()]).data('loaded', true)
                  pageDataReady = true
                } else {
                  missImg = true
                }
              }
            }

            // 本地全部找到则不继续
            if (!missImg) {
              logger.debug('本地缓存全部命中')
              pageMap[pageBlock.toString()] = true
              showView()
              return
            }

            if (remoteLoadLock) {
              // 正在远程加载中
              if (!!loadingParams && loadingParams[0] <= startPage && endPage <= loadingParams[1]) {
                logger.debug('重复任务正在加载中，丢弃：' + startPage + '-' + endPage)
                return
              }
              for (var j in loadQueue) {
                if (loadQueue[j][0] <= startPage && endPage <= loadQueue[j][1]) {
                  logger.debug('重复任务正在排队中，丢弃：' + startPage + '-' + endPage)
                  return
                }
              }
              logger.debug('正在远程加载中，将任务放入队列(queue length ' + loadQueue.length + ')：' + startPage + '-' + endPage)
              loadQueue.push([startPage, endPage])
            }

            logger.debug('开始远程加载：' + startPage + '-' + endPage)
            remoteLoadLock = true
            loadingParams = [startPage, endPage]
            $.remoteLoad({
              starPage: startPage,
              startPage: startPage,
              endPage: endPage
            }, function (json) {
              logger.debug('远程调用成功响应[' + startPage + '-' + endPage + ']：' + JSON.stringify(json))
              if (!json.error && !!json.data && json.data.TotalPages > 0) {
                totalPages = json.data.TotalPages
                if (!isInitPages) {
                  initAllBlankPage()
                  isInitPages = true
                }
                pageDataReady = true
                pageMap[pageBlock.toString()] = true
                $.each(json.data.Urls, function (i, o) {
                  var img = $('#img_page_' + o.Index)
                  if (!img.data('loaded')) {
                    logger.debug('从远程加载页：' + o.Index + ', ' + baseUrl + o.Url)
                    img.data('from', 'remote').attr('crossOrigin', 'Anonymous').attr('src', baseUrl + o.Url).data('loaded', true).show()
                  }
                })
                checkImageHeight(startPage, endPage)
                showView()
                setTimeout(scrollLoadNext, 200)
              } else {
                var errorCode
                if (json.code === 200) {
                  // 由转换服务返回的错误
                  switch (json.error.code) {
                    case 'DOWNLOAD_FAILED':
                      errorCode = '510'
                      break
                    case 'FILE_SIZE_OUT_OF_LIMIT':
                      errorCode = '511'
                      break
                    default:
                      errorCode = '502'
                      break
                  }
                } else {
                  // api返回的错误
                  errorCode = json.code.toString()
                }
                if (pageDataReady) {
                  setState2Retry(startPage, endPage)
                  if (pageBlock === lastScrollPageBlock) {
                    lastScrollPageBlock = -1
                  }
                } else {
                  $.throwError(errorCode, function () {
                    logger.debug('重试appendImg：' + startPage + '-' + endPage)
                    appendImg(startPage, endPage)
                  })
                }
              }
              remoteLoadLock = false
              loadingParams = null
              if (loadQueue.length > 0) {
                var params = loadQueue.pop()
                if (params) {
                  logger.debug('从队列提取任务：' + params[0] + '-' + params[1])
                  setTimeout(function () {
                    appendImg(params[0], params[1])
                  }, 0)
                }
              }
            }, function (XMLHttpRequest, textStatus, errorThrown) {
              logger.error('请求失败[' + startPage + '-' + endPage + ']：textStatus=' + textStatus + ',errorThrown=' + errorThrown)
              if (pageDataReady) {
                setState2Retry(startPage, endPage)
                if (pageBlock === lastScrollPageBlock) {
                  lastScrollPageBlock = -1
                }
              } else {
                var errorCode = '400'
                if (textStatus === 'timeout') {
                  errorCode = '504'
                }
                $.throwError(errorCode, function () {
                  logger.debug('重试appendImg：' + startPage + '-' + endPage)
                  appendImg(startPage, endPage)
                })
              }
              remoteLoadLock = false
              loadingParams = null
            })
          }

          function initAllBlankPage () {
            var imgDom = ''
            for (var i = 1; i <= totalPages; i++) {
              imgDom += '<div id="img_con_' + i + '" class="img-container" data-page="' + i + '">' +
                        '<div class="page-hd" data-page=' + i + '>HD</div>' +
                        '<div class="page-indicator">' + i + ' / ' + totalPages + '</div>' +
                        '<img id="img_page_' + i + '" class="img-content">' +
                        '<img id="img_loading_' + i + '" class="img-loading" src="' + loadingImg + '">' +
                        '<div id="img_loading_retry_' + i + '" class="img-loading-retry-button">' + $.i18n('retry') + '</div>' +
                        '</div>'
            }
            $('#viewBody').append(imgDom)

            // 图片加载完成后隐藏loading，抽取流本地缓存
            $('.img-content').on('load', function () {
              var img = $(this).data('success', true).show()
              var imgLoading = img.next()
              imgLoading.next().hide()
              imgLoading.remove()
              if (!imgDataReady) {
                $('.img-container').css('min-height', $(this).height() + 60)
                imgDataReady = true
              }
              if (!img.data('hd') && !!img.data('from') && img.data('from') === 'remote') {
                setTimeout(function () {
                  var base64Data = $.getImgBase64(img[0])
                  localUrlData[img.parent().data('page').toString()] = base64Data
                  $.SDK.cacheImg(totalPages, img.parent().data('page'), base64Data)
                }, 0)
              }
            }).on('error', function () {
              var img = $(this)
              img.removeData('loaded')
              var page = img.parent().data('page')
              if (!!img.data('success') && img.data('hd')) {
                // 加载高清图失败
                logger.debug('高清图片加载失败Page：' + page + '，' + img.attr('src'))
                img.removeData('hd').attr('src', localUrlData[page.toString()])
                img.parent().find('.page-hd-active').removeClass('page-hd-active').addClass('page-hd').removeData('hd_mode')
              } else {
                logger.debug('标清图片加载失败Page：' + page + '，' + img.attr('src'))
                var pageBlock = parseInt((page + pageStep - 1) / pageStep) - 1
                pageMap[pageBlock.toString()] = false
                if (pageBlock === lastScrollPageBlock) {
                  lastScrollPageBlock = -1
                }
                if (img.data('from') === 'local') {
                  // 如果加载失败的图片来自本地缓存就清除掉本地缓存
                  delete localUrlData[page.toString()]
                }
                img.hide().removeAttr('src').next().hide().next().show()
              }
            })

            $('.img-loading-retry-button').on('click', function () {
              var page = $(this).parent().data('page')
              var pageBlock = parseInt((page + pageStep - 1) / pageStep) - 1
              var startPage = pageBlock * pageStep + 1
              var endPage = Math.min(startPage + pageStep - 1, totalPages)
              logger.debug('用户发起重试Page：' + startPage + '-' + endPage)
              setState2Reload(startPage, endPage)
              setTimeout(function () {
                appendImg(startPage, endPage)
              }, 200)
            })

            $('.page-hd').click(function () {
              var btnHD = $(this)
              var page = btnHD.data('page')
              var target = $('#img_page_' + page)

              if (!!btnHD.data('hd_mode') || !target.data('success')) {
                return
              }

              $('#img_con_' + page).prepend('<div id="hd_mask_' + page + '" class="hd_mask"><img class="img-loading" style="display:inline" src="' + loadingImg + '"></div>')

              logger.debug('开始远程加载高清图：' + page)
              $.remoteLoad({
                imgLevel: 2,
                starPage: page,
                startPage: page,
                endPage: page
              }, function (json) {
                logger.debug('高清图远程调用成功响应[' + page + ']：' + JSON.stringify(json))
                var url = json.data.Urls[0].Url
                target.data('from', 'remote').data('hd', true).attr('crossOrigin', 'Anonymous').attr('src', baseUrl + url)
                btnHD.removeClass('page-hd').addClass('page-hd-active').data('hd_mode', true)
                $('#hd_mask_' + page).remove()
              }, function (XMLHttpRequest, textStatus, errorThrown) {
                logger.error('高清图请求失败[' + page + ']：textStatus=' + textStatus + ',errorThrown=' + errorThrown)
                target.removeData('hd')
                btnHD.removeData('hd_mode')
                $('#hd_mask_' + page).remove()
              })
            })
          }

          function setState2Reload (startPage, endPage) {
            $('.img-content').slice(startPage - 1, endPage).each(function () {
              var target = $(this)
              target.next().next().hide()
              if (!target.data('loaded')) {
                target.next().show()
              }
            })
          }

          function setState2Retry (startPage, endPage) {
            $('.img-content').slice(startPage - 1, endPage).each(function () {
              var target = $(this)
              target.next().hide()
              if (!target.data('loaded')) {
                target.hide().removeAttr('src').next().next().show()
              }
            })
          }

          function checkImageHeight (startPage, endPage) {
            if (imgDataReady) return
            $('.img-content').slice(startPage - 1, endPage).each(function () {
              if ($(this).height() > 0) {
                $('.img-container').css('min-height', $(this).height() + 60)
                imgDataReady = true
                return false
              }
            })
            if (!imgDataReady) {
              setTimeout(function () {
                checkImageHeight(startPage, endPage)
              }, 100)
            }
          }
        })(window.jQuery)
    </script>
</body>

</html>